from rest_framework import viewsets, response, status
from celery_client.app import app as celery_client
from celery_client.tasks import on_task_submitted

from .models import ShippingContainer, Task
from .serializers import ShippingContainerSerializer, TaskSerializer


class ShippingContainerViewSet(viewsets.ModelViewSet):

    serializer_class = ShippingContainerSerializer
    queryset = ShippingContainer.objects.all()


class TaskViewSet(viewsets.ModelViewSet):

    serializer_class = TaskSerializer
    queryset = Task.objects.all()

    def partial_update(self, request, *args, **kwargs):
        submit_now = request.data.pop('submit', False)
        super().partial_update(request, *args, **kwargs)
        instance = self.get_object()

        if submit_now:
            on_task_submitted.apply([{
                'tenant_id': request.user.tenant.id,
                'task_id': instance.id
            }])

            instance.refresh_from_db()

        return response.Response(
            TaskSerializer(instance).data,
            status=status.HTTP_200_OK
        )
